<?php

namespace addons\qingdong\controller;

use addons\qingdong\model\Daily as DailyModel;
use addons\qingdong\model\DailyRead;
use addons\qingdong\model\File;
use addons\qingdong\model\Form;
use addons\qingdong\model\Staff;
use addons\qingdong\model\Message;
use addons\qingdong\model\DailyDraft;
use think\Db;
use think\Exception;
/**
 * 工作报告接口
 */
class Daily extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];


    //创建
    public function createDaily()
    {
        $params = $this->request->post();

        Db::startTrans();
        try {
            $params['create_staff_id'] = $this->auth->id;
            $dailyId = DailyModel::createDaily($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('创建工作报告成功');
    }


    //获取
    public function getList()
    {
        $limit = input("limit/d", 10);
        $is_read = input('is_read', 0);
        $staff_ids = input('staff_id', 0);
        $type = input('type', 0);
        $times = input('times', '');

        $where = [];
        $where['create_staff_id'] = ['in', Staff::getMyStaffIds()];

        if ($staff_ids) {
            $where['create_staff_id'] = $staff_ids;
        }

        if ($type) {
            $where['type'] = $type;
        }
        if ($times) {//筛选时间
            $times = explode(',', $times);
            $where['createtime'] = ['between', [strtotime($times[0]), strtotime($times[1]) + 86400 - 1]];
        }
        $staff_id = $this->auth->id;
        if ($is_read == 1) {//已读
            $ids = DailyRead::where(['staff_id' => $staff_id])->column('daily_id');
            $where['id'] = ['in', $ids];
        } elseif ($is_read == 2) {//未读
            $ids = DailyRead::where(['staff_id' => $staff_id])->column('daily_id');
            $where['id'] = ['not in', $ids];
        }
        $followWhere = [];
        $elseWhere = [];
        if (!$staff_ids) {
            $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' . $this->auth->id . ',reminds_id)')];
            if ($type) {
                $elseWhere['type'] = ['eq', $type];
            }
            if ($is_read == 1) {//已读
                $elseWhere['id'] = ['in', $ids];
            } elseif ($is_read == 2) {//未读
                $elseWhere['id'] = ['not in', $ids];
            }
        }


        $records = DailyModel::where($where)->whereOr(function ($query) use ($followWhere, $elseWhere) {
            $query->where($followWhere)->where($elseWhere);
        })->with([
            'staff',
            'read' => function ($query) use ($staff_id) {
                $query->where(['staff_id' => $staff_id]);
            }
        ])->order('id desc')->paginate($limit)->toArray();

        $data = $records['data'];
        foreach ($data as $k => $v) {
            if (!empty($v['read'])) {
                $v['is_read'] = 1;
            } else {
                $v['is_read'] = 0;
            }
            $data[$k] = $v;
        }
        $this->success('请求成功', [
            'total' => $records['total'],
            'per_page' => $records['per_page'],
            'current_page' => $records['current_page'],
            'last_page' => $records['last_page'],
            'data' => $data
        ]);

        $this->success('请求成功', $records);
    }


    //获取详情
    public function getDailyDetail()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数不能为空');
        }
        $record = DailyModel::where(['id' => $id])->with([
            'staff',
        ])->find();
        if (empty($record)) {
            $this->error('记录不存在');
        }

        $record = $record->toArray();
        $reminds_id = $record['reminds_id'];
        $reminds_id = explode(',', $reminds_id);
        $names = Staff::where(['id' => ['in', $reminds_id]])->column('name');
        $record['staff_name'] = implode(',', $names);
        if ($record['other']) {
            if(is_array($record['other'])){
                $other  = $record['other'];
            }else{
                $other = json_decode($record['other'], true);
            }
        } else {
            $other = [];
        }
        $record = array_merge($record, $other);
        switch($record['type']){
            case '日报':
                $type = 'daily';
                break;
            case '周报':
                $type ='weekly';
                break;
            case '月报':
                $type = 'monthly';
                break;
            case '季报':
                $type = 'quarterly';
                break;
            case '年报':
                $type = 'yearly';
                break;
            default:
                $type = 'daily';
                break;
        }

        $form = Form::getDataValue($type,$record);
        foreach($form as $k=>$v){
            if($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile'){
                if(key_exists($v['id'],$record)){
                    if(isset($record[$v['id']]) && $record[$v['id']]){
                        $whereT['id'] = array('in',$record[$v['id']]);
                        $fileinfo = File::where($whereT)->field('id,name,file_path')->select();
                        if($fileinfo){
                            $record[$v['id']] = $fileinfo;
                        }
                    }
                }
            }
        }
        //标记通知已读
        Message::setRead(Message::DAILY_TYPE, $id, $this->auth->id);
        //添加阅读记录
        DailyRead::addRead($id, $this->auth->id);

        $this->success('请求成功', $record);
    }


    //获取工作报告已读 未读
    public function getDailyRead()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $daily = DailyModel::where(['id' => $id])->find();
        if (empty($daily)) {
            $this->error('记录不存在');
        }
        $create_staff_id = $daily['create_staff_id'];

        $read = DailyRead::where(['daily_id' => $id])->group('staff_id')->field('id,staff_id')->with(['staff'])->select();
        $staffIds = [];
        foreach ($read as $v) {
            $staffIds[] = $v['staff_id'];
        }
        //全部可看数据的人
        $allids = explode(',', $daily->reminds_id);
        $not_ids = array_diff($allids, $staffIds);

        $notRead = Staff::where(['id' => ['in', $not_ids]])
            ->field('id,name,img')->select();
        $this->success('请求成功', ['read' => $read, 'not_read' => $notRead]);
    }

    //草稿创建
    public function daily_draft()
    {
        $params = $this->request->post();

        Db::startTrans();
        try {
            $params['create_staff_id'] = $this->auth->id;
            //自定义字段
            $other = [];
            foreach ($params as $name => $val) {
                if (strstr($name, 'other_') !== false) {
                    if(is_array($val)){
                        $other[$name] = implode(',',$val);
                    }else{
                        $other[$name] = $val;
                    }
                    unset($params[$name]);
                }
            }
            $params['other'] = json_encode($other);
            $where['create_staff_id'] = $this->auth->id;
            $where['type'] = $params['type'];
            $info = DailyDraft::where($where)->find();
            if ($info) {
                $result = DailyDraft::where(array('id' => $info['id']))->update($params);
            } else {
                $result = DailyDraft::create($params);
            }

            if (false === $result) {
                // 验证失败 输出错误信息
                throw new Exception('草稿保存失败');
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('草稿保存成功');
    }

    //获取详情
    public function getDailyDraftDetail()
    {
        $type = input('type');
        if (!$type) {
            $this->error('参数不正确');
        }
        $where['create_staff_id'] = $this->auth->id;
        $where['type'] = $type;
        $record = DailyDraft::where($where)->find();
        if (empty($record)) {
            $this->success('记录不存在');
        }
        switch ($record['type']) {
            case '日报':
                $record['type_index'] = 0;
                break;
            case '周报':
                $record['type_index'] = 1;
                break;
            case '月报':
                $record['type_index'] = 2;
                break;
            case '季报':
                $record['type_index'] = 3;
                break;
            case '年报':
                $record['type_index'] = 4;
                break;
            default:
                $record['type_index'] = 0;
                break;
        }
        $record = $record->toArray();
        $reminds_id = $record['reminds_id'];
        $reminds_id = explode(',', $reminds_id);
        $names = Staff::where(['id' => ['in', $reminds_id]])->field('id,img,name,post')->select();
        $record['staff_info'] = $names;
        if ($record['other']) {
            $other = json_decode($record['other'], true);
        } else {
            $other = [];
        }
        $record = array_merge($record, $other);

        $this->success('请求成功', $record);
    }



    //修改工作报告
    public function updateDaily()
    {
        $params = $this->request->post();
        if(empty($params['id'])){
            $this->error('参数不能为空');
        }

        Db::startTrans();
        try {
            $dailyId = DailyModel::updateDaily($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('创建工作报告成功');
    }

}
